#!/usr/bin/python2.5
"""
BaseTest is a base class for Ignatz unit tests that sets up the app engine
API stubs in apiproxy_stub_map.

See 
http://groups.google.com/group/google-appengine/browse_thread/thread/9bf8102ae975c94c
for details on the App Engine stub setup code.

Copyright 2008 Ryan Barrett
"""

__author__ = 'Ryan Barrett <ignatz at ryanb dot org>'
__url__ = 'http://code.google.com/p/ignatz/'

import os
import time
import unittest

from google.appengine.api import apiproxy_stub_map
from google.appengine.api import datastore_file_stub
from google.appengine.api import mail_stub
from google.appengine.api import urlfetch_stub
from google.appengine.api import user_service_stub


APP_ID = 'ignatz-app'

class BaseTest(unittest.TestCase):
  """A base class for Ignatz unit tests that sets up the app engine stubs."""

  def assertEqual(self, x, y):
    """Override TestCase.assertEqual() to check both the value and the type.

    TODO(ryanb): rename this something else."""
    try:
      x_str = repr(x)
    except:
      x_str = str(sys.exc_info()[:2])

    try:
      y_str = repr(y)
    except:
      y_str = str(sys.exc_info()[:2])

    self.assert_(x.__class__ == y.__class__,
                 '%s != %s' % (x.__class__, y.__class__))
    self.assert_(x == y, 'Expected:\n%s\nBut received:\n%s' % (x_str, y_str))

  def setUp(self):
    os.environ['APPLICATION_ID'] = APP_ID

    # Ensure we work in UTC
    self.save_tz = os.environ.get('TZ')
    os.environ['TZ'] = 'UTC'
    time.tzset()

    # Use a fresh api proxy and stubs
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()

    datastore_stub = datastore_file_stub.DatastoreFileStub(
      APP_ID, '/dev/null', '/dev/null')
    apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', datastore_stub)

    apiproxy_stub_map.apiproxy.RegisterStub(
      'user', user_service_stub.UserServiceStub())
    os.environ['AUTH_DOMAIN'] = 'gmail.com'
    if 'USER_EMAIL' in os.environ:
      del os.environ['USER_EMAIL']

    apiproxy_stub_map.apiproxy.RegisterStub(
      'urlfetch', urlfetch_stub.URLFetchServiceStub())

    apiproxy_stub_map.apiproxy.RegisterStub(
      'mail', mail_stub.MailServiceStub()) 

  def tearDown(self):
    # Restoring original timezone settings
    if self.save_tz is None:
      del os.environ['TZ']
    else:
      os.environ['TZ'] = self.save_tz
    time.tzset()

  def login_user(self, email):
    os.environ['USER_EMAIL'] = email
